#include "db.h"

#include "in.h"

int test_insert_records_batch()
{
	struct MemDatabase	*db = NULL ;
	struct MemTable		*table = NULL ;
	struct MemIndex		*index = NULL ;
	struct UserInfo		user_info_array[ 10 ] ;
	size_t			user_info_array_count ;
	int			i ;
	
	int			nret = 0 ;
	
	printf( "MDBCreateDatabase ...\n" );
	db = MDBCreateDatabase( "mydb" ) ;
	if( db == NULL )
	{
		printf( "ERROR : MDBCreateDatabase failed[%d]\n" , MDBGetLastError() );
		return -1;
	}
	else
	{
		printf( "MDBCreateDatabase ok , db[%p]\n" , db );
	}
	
	printf( "MDBCreateTable mytable ...\n" );
	table = MDBCreateTable( db , "mytable" , sizeof(struct UserInfo) ) ;
	if( table == NULL )
	{
		printf( "ERROR : MDBCreateTable mytable failed[%d]\n" , MDBGetLastError() );
		return -1;
	}
	else
	{
		printf( "MDBCreateTable mytable ok , table[%p]\n" , table );
	}
	
	printf( "MDBCreateIndex myindex ...\n" );
	index = MDBCreateIndex( table , "myindex" , MDB_UNIQUEINDEX , MDBFIELD(struct UserInfo,uid) , MDBFIELD_NONE ) ;
	if( index == NULL )
	{
		printf( "ERROR : MDBCreateIndex myindex failed[%d]\n" , MDBGetLastError() );
		return -1;
	}
	else
	{
		printf( "MDBCreateIndex myindex ok , index[%p]\n" , index );
	}
	
	memset( & user_info_array , 0x00 , sizeof(user_info_array) );
	for( i = 0 ; i < sizeof(user_info_array)/sizeof(user_info_array[0]) ; i++ )
	{
		user_info_array[i].uid = i+1 ;
		snprintf( user_info_array[i].user_name , sizeof(user_info_array[i].user_name)-1 , "myname-%d" , i+1 );
		snprintf( user_info_array[i].email , sizeof(user_info_array[i].email)-1 , "myname-%d@163.com" , i+1 );
	}
	user_info_array_count = i ;
	
	nret = MDBInsertBatch( table , user_info_array , user_info_array_count ) ;
	if( nret )
	{
		printf( "MDBInsertBatch failed[%d]\n" , nret );
		return -1;
	}
	else
	{
		printf( "MDBInsertBatch ok\n" );
	}
	
	memset( user_info_array , 0x00 , sizeof(user_info_array) );
	printf( "MDBSelectBatch ...\n" );
	nret = MDBSelectBatch( table , user_info_array , sizeof(user_info_array)/sizeof(user_info_array[0]) , & user_info_array_count , MDBFIELD(struct UserInfo,uid) , MDBFIELD(struct UserInfo,user_name) , MDBFIELD(struct UserInfo,email) , MDBFIELD_NONE , NULL , MDBFIELD_NONE ) ;
	if( nret )
	{
		printf( "ERROR : MDBSelectBatch failed[%d]\n" , MDBGetLastError() );
		return -1;
	}
	else
	{
		printf( "MDBSelectBatch ok , user_info_array_count[%zu]\n" , user_info_array_count );
		for( i = 0 ; i < MIN(user_info_array_count,sizeof(user_info_array)/sizeof(user_info_array[0])) ; i++ )
		{
			printf( "    uid[%"PRIu32"] user_name[%s] email[%s]\n" , user_info_array[i].uid , user_info_array[i].user_name , user_info_array[i].email );
		}
	}
	
	printf( "MDBDropDatabase ...\n" );
	MDBDropDatabase( db );
	printf( "MDBDropDatabase ok\n" );
	
	return 0;
}

int main()
{
	return -test_insert_records_batch();
}

